<?php

//  对接文档
//http://47.96.6.128:8080/html/sup_doc.html
include_once "baseChannel.php";
// 时间相差8小时
// date_default_timezone_set("Asia/Shanghai");
class yinuo extends BaseChannel
{

    protected $appSecret;

    public function __construct($options)
    {
        parent::__construct($options);
        $this->appSecret = $options['appSecret'];
        $this->customerId = $options['customerId'];
        $this->headerArray =  [
            "Content-type" => "application/x-www-form-urlencoded"
        ];;
    }
    // 计算签名提单需要签名  emptyWithSign 为空参与签名
    public function getSign($data, $emptyWithSign = false)
    {
        foreach ($data as $key => $val) {
            if (!$emptyWithSign) {
                if (empty($val)) {
                    unset($data[$key]);
                }
            }
            if (isset($data['sign'])) {
                unset($data['sign']);
            }
        }
        ksort($data);
        $data['key'] = $this->appSecret;
        $str = http_build_query($data);
        $str = urldecode($str);
        $sign = strtoupper(md5($str));
        return $sign;
    }
    public function queryBalance($params = [])
    {
        $data['customerId'] = $this->customerId;
        $data['sign'] = $this->getSign($data);
        $url = $this->query_balance_url;
        $return_str = $this->httpRequest($url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        // var_dump($return_data);
        if ($return_data['return_code'] == 200) {
            return [
                'error' => 0,
                'msg' => $return_data['msg'] ?? '查询成功',
                'balance' => $return_data['balance'] / 100 ?? 0, //余额
                'credit' => 0, //授信 
                'code' => 200,
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['resultMsg'] ?? '查询失败',
            'code' => 500
        ];
    }
    public function queryOrder($params)
    {
        $data['customerId'] = $this->customerId;
        $data['orderNo'] = $params['push_order_sn'];
        $data['sign'] = $this->getSign($data);
        $url = $this->query_order_url;
        $return_str = $this->httpRequest($url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => $data, //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        $order_status = $return_data['status'];
        //处理中
        if ($return_data['return_code'] == 200 && $order_status == 2) {
            $ret['msg'] = $return_data['msg'] ?? '充值中';
        }
        // 成功
        if ($return_data['return_code'] == 200 && $order_status == 3) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['msg'];
        }
        // 失败
        if ($return_data['code'] == 0 && $order_status == 5) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败:' . $return_data['msg'];
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $data = [];
        $data['customerId'] = $this->customerId;
        $data['orderNo'] = $params['push_order_sn'];
        $data['notifyUrl'] = $this->callback_url;
        $data['phoneNumber'] = $mobile;
        $data['price'] = $params['face_value'] * 100;
        $data['operator'] = $params['isp'];
        $data['chargeType'] = $params['hf_type'];

        $data['sign'] = $this->getSign($data);

        $return_str = $this->httpRequest($this->submit_order_url, 'POST', $data, '', '');
        $return_data = json_decode($return_str, 1);
        $ret = [
            'url' => $this->submit_order_url,
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' =>  null,
            'channel_balance' => null,
        ];

        if ($return_data['return_code'] == 200) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['msg'] ?? '下单成功';
        } else {
            if (isset($return_data['return_code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['msg'] ?? '下单失败';
            }
        }
        return $ret;
    }
    public function callback($params)
    {
        $this->callback_params = $params;
        $this->channel_order_sn = $params['serialNumber'];
        $this->push_order_sn = $params['orderNo'];
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $params['status'];
        $msg = null;
        //凭证
        // $pz =  $params['voucher'] ?? '';
        // 验证签名
        $sign = $this->getSign($params);
        if ($sign !== $params['sign']) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            $res['sign'] = $sign;
            return $res;
        }
        if ($order_status == 3) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] =   $msg ?? '充值完成';
            $res['resp_data'] = 'success';
        }
        if ($order_status == 5) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] =  $msg ?? '充值失败';
        }
        //初始化就是充值中
        if ($order_status == 2) {
            $res['order_status'] = 2;
            $res['msg'] = $msg ?? '充值中';
        }
        return $res;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate($isSecond = false)
    {
        if ($isSecond) {
            return time();
        } else {
            $time = $this->msectime();
            $timestamp = time() . substr($time, -3);
            return $timestamp;
        }
    }
}
